package com.sh.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.sh.cache.BindingCache;
import com.sh.constant.BindResult;
import com.sh.dto.BindingInfo;
import com.sh.model.DeviceBind;
import com.sh.service.DeviceBindService;
import com.sh.util.Counter;

/**
* @comments 绑定功能
* @author  zg
* @date 2018年4月5日
*/
@RestController
@RequestMapping("/binding")
public class BindingController {
	private Logger logger = LogManager.getLogger(this.getClass());
	
	@Autowired
	private DeviceBindService deviceBindService;
	
	//@Autowired
	//private MqttUtils mqttUtils;
	
	/**
	 * 硬件设备的绑定请求
	 * @author zg
	 * @date 2018年4月5日
	 * @return
	 */
	@RequestMapping("/device")
	public String device(BindingInfo param) {
		logger.info("param:{}", JSON.toJSONString(param));
		if(param == null || StringUtils.isBlank(param.getSn())) {
			return "fail";
		}

		String bindKey = param.getSn() + "-" + param.getMac();
		BindingCache.addDeviceInfo(bindKey);
		
		BindResult result = BindingCache.checkBindingApp(bindKey, new Counter());
		if(result == BindResult.SUCESS) {
			return "success";
		}else if(result == BindResult.TIMEOUT){
			return "timeout";
		}
		return "fail";
	}
	
	/**
	 * 手机APP的绑定请求
	 * @author zg
	 * @date 2018年4月5日
	 * @return
	 */
	@RequestMapping("/app")
	public String app(BindingInfo param) {
		logger.info("param:{}", JSON.toJSONString(param));
		if(param == null || StringUtils.isBlank(param.getSn()) || StringUtils.isBlank(param.getMobile())) {
			return "fail";
		}
		
		String bindKey = param.getSn() + "-" + param.getMac();
		BindingCache.addAppInfo(bindKey, param.getMobile());
		
		BindResult result = BindingCache.checkBindingDevice(bindKey, new Counter());
		
		if(result == BindResult.SUCESS) {
			//绑定成功，存入数据库
			deviceBindService.saveBindingInfo(new DeviceBind(param.getSn(), param.getMac(), param.getMobile()));
			return "success";
		}else if(result == BindResult.TIMEOUT){
			return "timeout";
		}
		
		return "fail";
	}
	
	
	@RequestMapping("/device-info")
	public Object deviceBindInfo() {
		//BindingCache bc = new BindingCache();
		//logger.info("BindingCache.getCheckFrequency：{}",BindingCache.getCheckFrequency());
		return BindingCache.getDeviceInfo();
	}
	
	@RequestMapping("/app-info")
	public Object appBindInfo() {
		
		return BindingCache.getAppInfo();
	}
	

}
